<template>
    <el-container>
    <el-aside width="15%"></el-aside>
    <el-main>
        <el-row>
            <el-col :span="20">
                <el-alert v-if="unlockParkspaceId" 
                :title="`您之前解锁的是${unlockParkspaceId}号车位，请输入缴费金额（如果您停入的不是该车位，请点击'清除记录'按钮，并输入您停入的车位编号）`" 
                type="info" show-icon></el-alert>
            </el-col>
            <el-col :span="4">
                <el-button v-if="unlockParkspaceId" size="mini" round @click="clearRecord">清除记录</el-button>
            </el-col>
        </el-row>

        <el-alert v-if="!unlockParkspaceId" title="请输入您停入的车位编号和缴费金额" type="info" show-icon></el-alert>
        <el-divider></el-divider>
        <!--表单-->
        <el-row :gutter="20">
            <el-col :offset="6" :span="6">
                <el-input v-model="id" type="number" clearable>
                    <template slot="prepend">车位编号</template>
                </el-input>
            </el-col>
            <el-col :span="3">
                <el-button v-on:click="getParkingById(id)">查看车位状态</el-button>
            </el-col>
        </el-row>
        <el-divider></el-divider>

        <el-row :gutter="20">
            <el-col :offset="6" :span="12">
                <div style='font-size:32px;font-family: Helvetica Neue;border-radius:12px;background-color:lightskyblue;box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2)'>
                    停车时间<br>
                    <i class="el-icon-time"></i>
                    <span>{{timeStr}}</span><br>
                    停车费用<br>
                    <i class="el-icon-goods"></i>
                    <span>{{payMoney}}</span>元<br>
                </div>
            </el-col>
        </el-row>

        <el-divider></el-divider>
        <el-row :gutter="20">
            <el-col :span="24">
                <el-button v-on:click="getCost">查看费用</el-button>
                <el-button type="primary" v-on:click="showPayPrompt">缴费</el-button>
            </el-col>
        </el-row>

        <el-divider></el-divider>
    </el-main>
    <el-aside width="15%"></el-aside>
</el-container>
</template>

<script>
import axios from 'axios'
export default {
    name: 'Pay',
    data() {
        return {
            id: null,
            parkingSpace: null,
            payMoney: null,
            time: 0,//秒
            timeStr: "0:00",
            timerId: null,
            unlockParkspaceId: null,
        }
    },
    methods: {
        getParkingById (id) {
            if (id == null) {
                this.showMessage('warning', '请输入车位编号！');
                return;
            }
            var that = this;
            axios.get("/park/" + id).then(
                function (response) {
                    var parkingSpace = response.data;
                    if (parkingSpace.status == 1) {
                        that.parkingSpace = response.data;
                        that.showMessage('info', "startTime:" + that.parkingSpace.startTime);
                        var date = new Date(that.parkingSpace.startTime);
                        that.startTimer(date);
                    } else {
                        that.showMessage('warning', "该车位没有停车");
                    }
                }, function (err) {
                    console.log(err);
                }
            );
        },
        startTimer (startTime) {
            if (this.timerId != null) {
                clearInterval(this.timerId);
            }
            var now = new Date();
            this.time = Math.trunc((now.getTime() - startTime.getTime()) / 1000);
            var that = this;
            this.timerId = setInterval(function () {
                that.time++;
                var time = that.time;
                var seconds = time % 60
                var minutes = Math.trunc(time / 60);
                var hours = Math.trunc(minutes / 60);
                minutes = minutes % 60;

                that.payMoney = Math.trunc(time / 60);

                that.timeStr = (hours > 0 ? hours.toString() + ":" : "")
                    + (minutes < 10 ? ('0' + minutes.toString()) : minutes.toString()) + ":"
                    + (seconds < 10 ? ('0' + seconds.toString()) : seconds.toString());
            }, 1000);
        },

        showMessage (type, message) {
            this.$message({
                message: message,
                type: type
            });
        },

        getCost () {
            if (this.id == null || this.id == "") {
                this.showMessage('warning', '请输入车位编号！');
                return;
            }
            var that = this;
            axios.get("/park/cost/" + this.id).then(
                function (response) {
                    var money = response.data.res;
                    if (money != null) {
                        that.showAlert(that.id + '号车位实时费用为' + response.data.res + '元', '查看费用');
                        that.payMoney = money;
                    } else {
                        that.showAlert(that.id + '号车位无需缴费', '查看费用');
                    }
                },
                function (err) {
                    console.log(err);
                }
            );
        },
        showAlert (msg, title) {
            this.$alert(msg, title, {
                confirmButtonText: '确定',
                // callback: action => {
                //     this.$message({
                //         type: 'info',
                //         message: `action: ${action}`
                //     });
                // }
            });
        },
        showPayPrompt () {//消息对话框
            this.$prompt('请输入金额', '缴费', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                    inputPattern: /^\d{1,}$/,
                    inputErrorMessage: '金额格式不正确'
            }).then(({value}) => {
                this.pay(value);
                // this.$message({
                //     type: 'success',
                //     message: '你的邮箱是: ' + value
                // });
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '取消输入'
                // });
            });
        },
        pay (money) {//缴费
            if (this.id == null || this.id == "") {
                this.showMessage('warning', '请输入车位编号！');
                return;
            }
            if (money == null || money == "" ) {
                this.showMessage('warning', '请输入正确金额！');
                return;
            }
            var that = this;
            axios({
                method: "post",
                url: "/park/cost",
                params: {
                    id: this.id,
                    money: money
                }
            }).then(
                function (response) {
                    that.showMessage('info', response.data.msg);
                    if (response.data.flag) {
                        that.payMoney = 0;
                        that.time = 0;
                        that.timeStr = 0;
                        that.parkingSpace = response.data.res;
                        clearInterval(that.timerId);
                        //清掉localstroage中的解锁车位id
                        localStorage.removeItem('unlock_parkspace_id')
                    }
                },
                function (err) {
                    console.log(err);
                }
            );
        },
        clearRecord() {
            localStorage.removeItem('unlock_parkspace_id')
            this.showMessage('info', '已清除记录，请输入您停入的车位编号')
        }
    },
    mounted() {
        //从localStorage获取之前解锁的车位，这个车位可能是用户停入的车位
        let unlockParkspaceId = localStorage.getItem('unlock_parkspace_id')
        if (unlockParkspaceId) {
            this.id = unlockParkspaceId //输入的id
            this.unlockParkspaceId = unlockParkspaceId //localstorage中的id
            this.getParkingById(this.id)
        }
    }
}
</script>

<style scoped>
    .el-aside {
        background-color: whitesmoke;
        color: #333;
        text-align: center;
        line-height: 200px;
    }

    .el-main {
        background-color: #E9EEF3;
        color: #333;
        text-align: center;
        line-height: 60px;
        padding-top: 0px;
        padding-bottom: 0px;
        overflow: hidden;
    }

    body > .el-container {
        margin-bottom: 40px;
    }

    .el-container:nth-child(5) .el-aside,
    .el-container:nth-child(6) .el-aside {
        line-height: 260px;
    }

    .el-container:nth-child(7) .el-aside {
        line-height: 320px;
    }
</style>